<template>
  <div class="mod-user">
    <div class="mod-user">
      <el-form :model="query" :inline="true" @keyup.enter.native="searchLanguagePoints()">
        <el-form-item>
          <el-input v-model="query.keyWord" clearable placeholder="知识点内容"></el-input>
        </el-form-item>

        <el-form-item>
          <el-select
            @change="changeSchoolType"
            v-model="query.school_type"
            filterable
            clearable
            placeholder="请选择所属阶段">
            <el-option
              v-for="item in schoolTypeList"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="query.grade_type"
            filterable
            clearable
            placeholder="请选择年级">
            <el-option
              v-for="item in gradeTypeListForQuery"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-if="hasPermission(['system:languagePoints:list'])" type="success" icon="el-icon-search" @click="searchLanguagePoints">查询</el-button>
          <el-button v-if="hasPermission(['system:languagePoints:save'])" type="primary" @click="addLanguagePoints">新增</el-button>
          <!--  <el-button v-if="hasPermission(['system:languagePoints:batchDelete'])" @click="batchDelete" type="danger">批量删除</el-button>-->
        </el-form-item>
      </el-form>
      <el-table
        :data="treeLanguagePointsList"
        :indent="10"
        border
        row-key="value"
        v-loading="loading"
        lazy
        :load="loadChildren"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        style="width: 100%;">

        <el-table-column
          prop="label"
          header-align="center"
          align="center"
          label="知识点内容">
        </el-table-column>


        <el-table-column
          prop="grade_type"
          header-align="center"
          align="center"
          label="所属阶段">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.school_type === 1" size="small">小学</el-tag>
            <el-tag v-else-if="scope.row.school_type === 2" size="small">初中</el-tag>
            <el-tag v-else="scope.row.school_type === 3" size="small">高中</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="grade_type"
          header-align="center"
          align="center"
          label="所属年级">
          <template slot-scope="scope">
            <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="subject_name"
          header-align="center"
          align="center"
          label="所属科目">
        </el-table-column>

        <el-table-column
          prop="create_date"
          header-align="center"
          align="center"
          width="180"
          :formatter="formatterCreateDate"
          label="创建时间">
        </el-table-column>

        <el-table-column
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="warning"
              v-if="hasPermission(['system:languagePoints:update'])"
              @click="updateLanguagePoints(scope.row)">修改</el-button>
            <el-button
             size="small"
             type="danger"
             v-if="hasPermission(['system:course:deleteById'])"
             @click="deleteLanguagePointsById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="sizeChangeHandler"
        @current-change="currentChangeHandler"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <el-dialog
        :title="!form.id ? '新增知识点' : '修改知识点'"
        :close-on-click-modal="false"
        :visible.sync="showFlag">
        <el-form :model="form" :rules="rules" ref="form" @keyup.enter.native="saveOrUpdate()" label-width="120px">
          <el-form-item label="知识点内容" prop="name">
            <el-input v-model="form.name" placeholder="知识点内容"></el-input>
          </el-form-item>

          <el-form-item label="所属阶段" placeholder="所属阶段" prop="school_type">
            <el-select
              @change="changeSchoolType"
              v-model="form.school_type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in schoolTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属年级" placeholder="所属年级" prop="grade_type">
            <el-select
              @change="changeGradeType"
              v-model="form.grade_type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in changeGradeTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属科目" placeholder="所属科目" prop="subject_id">
            <el-select
              @change="changeSubject"
              v-model="form.subject_id"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in changeSubjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="排序">
            <el-input v-model="form.sort" placeholder="排序(数字越大,排名越靠前)"></el-input>
          </el-form-item>

          <el-form-item label="所属父级" placeholder="父级知识点">
            <el-cascader
              clearable
              :options="formTreeLanguagePointsList"
              v-model="form.parentIdArray"
              change-on-select>
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer"  class="dialog-footer">
          <el-button @click="showFlag = false">取消</el-button>
          <el-button type="primary" @click="saveOrUpdateLanguagePoints()">确定</el-button>
       </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
    /* eslint-disable no-unused-vars,no-trailing-spaces,no-redeclare */
    import { changeGradeTypeApi, changeSchoolTypeApi } from '@/utils/education-api'
    import { getSchoolTypeListApi, getGradeTypeListApi, getDictValueListByParentId } from '@/utils/system-dict-api'
    let thisPage = null
    export default {
        name: 'languagePoints',
        data () {
            return {
                grade_type: '',
                currentPage: 1,
                pageSize: 10,
                totalCount: 0,
                treeLanguagePointsList: [],
                formTreeLanguagePointsList: [],
                showFlag: false,
                form: {
                    name: '',
                    parentIdArray: [],
                    parent_id: '',
                    grade_type: '',
                    school_type: '',
                    subject_id: '',
                    sort: 0
                },
                gradeTypeListForQuery: [],
                loading: false,
                query: {
                    keyWord: '',
                    grade_type: '',
                    school_type: ''
                },

                rules: {
                    name: {
                        required: true, message: '请输入知识点内容', trigger: 'blur'
                    },
                    school_type: {
                        required: true, message: '请选择阶段', trigger: 'blur'
                    },
                    grade_type: {
                        required: true, message: '请选择年级', trigger: 'blur'
                    },
                    subject_id: {
                        required: true, message: '请选择科目', trigger: 'blur'
                    }
                },
                subjectList: [], // 科目列表
                schoolTypeList: [],
                gradeTypeList: [],
                changeGradeTypeList: [],
                changeSubjectList: []
            }
        },

        beforeCreate () {
            thisPage = this
        },

        watch: {
            /*'form.grade_type' (val) {
                this.query.grade_type = val
                this.getTreeLanguagePointsList(true)
            },*/

           /* 'form.subject_id' (val) {
                this.query.subject_id = val
                this.getTreeLanguagePointsList(true)
            }*/
        },

        mounted () {
            let that = this
            getGradeTypeListApi((data) => {
                that.gradeTypeList = data
                that.changeGradeTypeList = data
                that.gradeTypeListForQuery = data
            })
            getSchoolTypeListApi((data) => {
                that.schoolTypeList = data
            })
            that.getParentLanguagePointsList() // 获取最顶级父类知识点
        },

        methods: {

            deleteLanguagePointsById (item) {
                this.$message.error('功能开发中,敬请期待')
            },

            sizeChangeHandler (val) {
                this.pageSize = val
                this.currentPage = 1
                this.getParentLanguagePointsList()
            },

            currentChangeHandler (val) {
                this.currentPage = val
                this.getParentLanguagePointsList()
            },

            loadChildren (tree, treeNode, resolve) {
                this.axios.get(this.$http.httpUrl('/system/languagePoints'), {
                    params: {
                        parentId: tree.value
                    }
                }).then(response => {
                   resolve(response.data.data.dataList)
                })
            },

            searchLanguagePoints () {
                this.currentPage = 1
                this.getParentLanguagePointsList()
            },

            updateLanguagePoints (item) {
                let that = this
                that.axios.get(that.$http.httpUrl('/system/languagePoints/findById'), {
                    params: {
                        id: item.value
                    }
                }).then(function (response) {
                    let result = response.data.data
                    that.form = result
                    that.form.parentIdArray = result.parentIdArray
                    that.changeSubjectList = result.subjectList
                    that.formTreeLanguagePointsList = result.languagePointsList
                    delete (that.form.subjectList)
                    delete (that.form.languagePointsList)
                    that.showFlag = true
                })
            },

            changeSubject (val) {
                this.axios.get(this.$http.httpUrl('/system/languagePoints'), {
                    params: {
                        gradeType: this.form.grade_type,
                        subjectId: val,
                        lazy: 'false'
                    }
                }).then(response => {
                    this.formTreeLanguagePointsList = response.data.data.dataList
                })
            },

            getParentLanguagePointsList () {
                this.axios.get(this.$http.httpUrl('/system/languagePoints'), {
                    params: {
                        offset: (this.currentPage - 1) * this.pageSize,
                        limit: this.pageSize,
                        gradeType: this.query.grade_type,
                        subjectId: this.query.subject_id,
                        schoolType: this.query.school_type,
                        keyWord: this.query.keyWord,
                        parentId: 0
                    }
                }).then(response => {
                    this.loading = false
                    this.treeLanguagePointsList = response.data.data.dataList
                })
            },

            clearForm (that) {
                that.form = {
                    name: '',
                    parentIdArray: [],
                    parent_id: '',
                    grade_type: '',
                    school_type: '',
                    subject_id: '',
                    sort: 0
                }
            },

            saveOrUpdateLanguagePoints () {
                let that = this
                let parentId = 0 // 取最后一位作为父类id
                if (that.form.parentIdArray) {
                    let parentIdsLength = that.form.parentIdArray.length
                    if (parentIdsLength > 0) {
                        parentId = that.form.parentIdArray[parentIdsLength - 1]
                    }
                }
                delete (that.form.parentIdArray)
                that.$refs['form'].validate(function (valid, rules) {
                    if (valid) {
                        that.form.parent_id = parentId
                        that.axios.post(that.$http.httpUrl('/system/languagePoints'), that.form)
                            .then(function (response) {
                                that.showFlag = false
                                if (response.data.code === 1) {
                                    that.$message({
                                        type: 'success',
                                        message: response.data.message
                                    })
                                    that.clearForm(that)
                                    that.query = {
                                        keyWord: '',
                                        grade_type: '',
                                        school_type: ''
                                    }
                                    that.getParentLanguagePointsList()
                                } else {
                                    that.$message({
                                        type: 'error',
                                        message: response.data.message
                                    })
                                }
                            }).catch(function (error) {
                            console.log(error)
                        })
                    } else {
                        let message = ''
                        for (let rule in rules) {
                            message = rules[rule][0].message
                            if (message) {
                                break
                            }
                        }
                        that.$message({
                            type: 'error',
                            message: message
                        })
                        return false
                    }
                })
            },

            changeSchoolType (val) {
                let that = this
                if (that.form.grade_type) {
                    that.form.grade_type = ''
                }
                let parentId = null
                that.schoolTypeList.forEach(item => {
                    if (val === item.code) {
                        parentId = item.id
                    }
                })
                getDictValueListByParentId(parentId, 'grade_type', data => {
                    that.changeGradeTypeList = data
                })
            },

            changeGradeType (val) {
                let that = this
                if (that.form.subject_id) {
                    that.form.subject_id = ''
                }
                changeGradeTypeApi(val, function (data) {
                    that.changeSubjectList = data
                })
            },

            addLanguagePoints () {
                this.showFlag = true
                this.form = {
                    name: '',
                    grade_type: '',
                    parentIdArray: [],
                    parent_id: '',
                    school_type: '',
                    subject_id: '',
                    sort: 0
                }
            },
            // 每页数
            sizeChangeHandler (val) {
                this.pageSize = val
                this.currentPage = 1
                this.getTreeLanguagePointsList(false)
            },

            // 当前页
            currentChangeHandler (val) {
                this.currentPage = val
                this.getTreeLanguagePointsList(false)
            },

            deleteLanguagePointsById (item) {
                let that = this
                item.sqlId = 'system.common.deleteById'
                item.table = 'course_info'
                that.$confirm('确定删除知识点' + item.name + '?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    that.axios.delete(that.$http.httpUrl('/system/languagePoints'), {
                        data: item
                    }).then(function (response) {
                        if (response.data.code === 1) {
                            that.$message({
                                type: 'success',
                                message: response.data.message
                            })
                            that.getTreeLanguagePointsList(false)
                        } else {
                            that.$message({
                                type: 'error',
                                message: response.data.message
                            })
                        }
                    })
                })
            },

            getSchoolType () {
                let that = this
                that.axios.get(that.$http.httpUrl('/api/pagination'), {
                    params: {
                        'sqlId': 'system.dict.get',
                        'type': 'school_type'
                    }
                }).then(function (response) {
                    that.schoolTypeList = response.data.data
                })
            },

            formatterCreateDate (row, column) {
                if (!row.create_date) {
                    return '--'
                }
                return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
            },

            getGradeType () {
                let that = this
                that.axios.get(that.$http.httpUrl('/api/pagination'), {
                    params: {
                        'sqlId': 'system.dict.get',
                        'type': 'grade_type'
                    }
                }).then(function (response) {
                    that.gradeTypeList = response.data.data
                    that.changeGradeTypeList = response.data.data
                })
            },

            getSubjectList () {
                let that = this
                that.axios.get(that.$http.httpUrl('/system/subject/list'), {
                    params: {
                        sqlId: 'system.subject.list'
                    }
                }).then(function (response) {
                    that.subjectList = response.data.data
                    that.changeSubjectList = response.data.data
                })
            }
        },

        filters: {
            getGradeName (gradeType) {
                for (let i in thisPage.gradeTypeList) {
                    if (thisPage.gradeTypeList[i].code === gradeType) {
                        return thisPage.gradeTypeList[i].value
                    }
                }
            }
        }
    }
</script>
<style>
  .el-table__expand-icon {
    display: inline-block;
    margin-right: 15px;
    vertical-align:-5px;
  }
</style>
